//
//  LGControllerInfoViewController.m
//  ALS3.0
//
//  Created by guomianxiang on 17/3/15.
//  Copyright © 2017年 guomianxiang. All rights reserved.
//

#import "LGControllerInfoViewController.h"

#import "UIView+LG.h"
//#import "LGtools.h"
//#import "ALSBarButton.h"
#import "SVProgressHUD.h"
//#import "ALSConstNSString.h"
#import "ALSHeader.h"
#import "LGDCTableHead.h"

#define k_name 0
#define k_sn 1
#define k_ip 2
#define k_port 3

#define k_section_controller 0
#define k_section_door 1

#define k_height_headCell 124
#define k_height_editCell_Presentation 52
#define k_height_editCell_Default 44
#define k_height_controllerCell 68

#define k_heightForHeaderInSection 35;
//#import "LGControllerInfoTool.h"
//#import "LGControllerHead.h"

@interface LGControllerInfoViewController ()<UITableViewDelegate, UITableViewDataSource,LGDCDelegate>
@property (weak, nonatomic) IBOutlet UITableView *controllerInfoTableView;
//@property (strong, nonatomic) UIButton *rightBarButton;
@property (strong, nonatomic) NSMutableArray<NSMutableArray<LGDCCellContent *>*> *tableDataArr;
@property (assign, nonatomic) LGControllerInfoViewState controllerInfoViewState;
@property (assign, nonatomic) CGFloat editingCellBottom;
@property (strong, nonatomic) NSIndexPath *editingCellIndexPath;
@end

@implementation LGControllerInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNotification];
    [MobClick beginLogPageView:UMPageName];

    k_registerNib(self.controllerInfoTableView)
    
    // 选择controllerInfoViewState 不是show 就是 add
    if (self.editControllerItem != nil) {
        self.controllerInfoViewState = LGControllerInfoViewShowState;
    }else {
        self.controllerInfoViewState = LGControllerInfoViewAddState;
    }
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [MobClick endLogPageView:UMPageName];

}

- (void)setupNotification {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

- (void)setLeftBarButtonWithTitle:(NSString *)title {
    UIButton *left = [ALSBarButton backButtonWithTitle:title];
    [left addTarget:self action:@selector(leftBatButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:left];
}

- (void)setRightBarButtonWithNormalTitle:(NSString *)normalTitle selectedTitle:(NSString *)selectedTitle highlightTitle:(NSString *)highlightTitle{
    
    UIButton *right = [ALSBarButton normalButtonWithNormalTitle:normalTitle selectedTitle:selectedTitle highlightTitle:highlightTitle];
    
    [right addTarget:self action:@selector(rightBatButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:right];
    
    //    self.rightBarButton = [ALSBarButton normalButtonWithNormalTitle:normalTitle selectedTitle:selectedTitle highlightTitle:highlightTitle];
    //
    //    [self.rightBarButton addTarget:self action:@selector(rightBatButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    //    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBarButton];
}

- (void)setShowState {
    self.tableDataArr = [LGDCCellContent transfromShowControllerInfoCellContentArrWithController:self.editControllerItem];
    
    [self setLeftBarButtonWithTitle:nil];
    self.navigationItem.title = @"控制器详情";
    
    UIButton *rightButton = [ALSBarButton normalButtonWithNormalTitle:nil andNormalImageName:@"edit" selectedTitle:nil andSelectedImageName:nil highlightTitle:nil andHighlightImageName:@"edit-in"];
    
    [rightButton addTarget:self action:@selector(rightBatButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    
    //    [self setRightBarButtonWithNormalTitle:@"编辑" selectedTitle:@"保存" highlightTitle:@"编辑"];
}

- (void)setEditState {
    
    self.tableDataArr = [LGDCCellContent transfromEditControllerInfoCellContentArrWithController:self.editControllerItem];
    
    [self setLeftBarButtonWithTitle:@"取消"];
    self.navigationItem.title = @"编辑控制器";
    [self setRightBarButtonWithNormalTitle:@"保存" selectedTitle:@"保存" highlightTitle:@"保存"];
}

- (void)setAddState {
    self.tableDataArr = [LGDCCellContent transfromAddControllerInfoCellContentArrWithController:self.addControllerItem];
    [self setLeftBarButtonWithTitle:@"取消"];
    self.navigationItem.title = @"添加控制器";
    [self setRightBarButtonWithNormalTitle:@"添加" selectedTitle:@"添加" highlightTitle:@"添加"];
}

- (void)rightBatButtonClick:(UIButton *)sender {
    [self.view endEditing:YES];
    
    switch (self.controllerInfoViewState) {
        case LGControllerInfoViewShowState:
            // 即  点击“编辑”
//            [[NSUserDefaults standardUserDefaults]boolForKey:ALSAdministrators]
            if (NSUDIsAdministrators) {
                self.controllerInfoViewState = LGControllerInfoViewEditState;
            }else {
                [SVProgressHUD showInfoWithStatus:@"请联系管理员"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
            }
            break;
        default:
            // 其他状态  点击 “保存” 或 “添加”
            [self save];
            break;
    }
}

- (void)leftBatButtonClick:(UIButton *)sender {
    [self.view endEditing:YES];
    switch (self.controllerInfoViewState) {
        case LGControllerInfoViewShowState:
            
            if (self.addControllerItem) {
                [self.navigationController popToViewController:self.navigationController.childViewControllers[1] animated:YES];
            }else {
                [self.navigationController popViewControllerAnimated:YES];
            }
            break;
        case LGControllerInfoViewEditState:
            
            self.controllerInfoViewState = LGControllerInfoViewShowState;
            break;
        case LGControllerInfoViewAddState:
            [self.navigationController popViewControllerAnimated:YES];
            break;
        default:
            break;
    }
}

- (BOOL)validateAllData {
    
    BOOL controllerInfoRight = YES;
    BOOL doorInfoRight = YES;
    
    NSMutableArray *infoArr = self.tableDataArr[k_section_controller];
    
    for (int i=0; i<infoArr.count; i++) {
        if (![self validateWithContent:infoArr[i]]) {
            // 控制器信息错误
            controllerInfoRight = NO;
        }
    }
    
    infoArr = self.tableDataArr[k_section_door];
    int count = 0;
    for (int i=0; i<infoArr.count; i++) {
        if (![self validateWithContent:infoArr[i]]) {
            count ++;
        }
    }
    if (count == infoArr.count) {
        // 门信息全部为空
        for (int i=0; i<infoArr.count; i++) {
            LGDCCellContent *content = infoArr[i];
            if (content.cellHeight == k_height_editCell_Default) {
                content.cellHeight = k_height_editCell_Presentation;
                content.presentationText = @"至少填写一扇门的名称";
                [self.controllerInfoTableView reloadRowsAtIndexPaths:@[content.indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
            }
        }
        doorInfoRight = NO;;
    }
    
    if (!controllerInfoRight || !doorInfoRight) {
        return NO;
    }
    return YES;
}

- (void)save {
    [self.view endEditing:YES];
    //校验数据
    if (![self validateAllData]) {
        return;
    }
    //禁止交互
    [self.controllerInfoTableView setUserInteractionEnabled:NO];
    //保存数据
    LGController *controller = [LGDCCellContent transfromLGControllerItemWithCellContentArr:self.tableDataArr];
    
    
    self.editControllerItem = controller;
    
    __weak LGControllerInfoViewController *weakSelf = self;
    
    switch (self.controllerInfoViewState) {
        case LGControllerInfoViewEditState:
        {
            [DCMI editItem:controller reply:^(BOOL success, NSError *error) {
                [weakSelf showSaveResulte:success andError:error completion:^{
                    //                    weakSelf.editControllerItem = controller;
                    weakSelf.controllerInfoViewState = LGControllerInfoViewShowState;
                }];
            }];
        }
            break;
        case LGControllerInfoViewAddState:
        {
            [DCMI addItem:controller reply:^(BOOL success, NSError *error) {
                [weakSelf showSaveResulte:success andError:error completion:^{
                    weakSelf.controllerInfoViewState = LGControllerInfoViewShowState;
                }];
            }];
        }
            break;
            
        default:
            break;
    }
}

- (void)showSaveResulte:(BOOL)success andError:(NSError *)error completion:(void(^)())completion {
    __weak LGControllerInfoViewController *weakSelf = self;
    
    if (success) {
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            completion();
            [weakSelf.controllerInfoTableView setUserInteractionEnabled:YES];
            
        });
        
    }else {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [weakSelf.controllerInfoTableView setUserInteractionEnabled:YES];
        });
        
    }
}


#pragma mark - UITableViewDataSource

k_tableViewDataSourceAndCellHeight(tableDataArr, self)

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view;
    
    switch (self.controllerInfoViewState) {
        case LGControllerInfoViewShowState:
            if (section == 1) {
                view = [self tableViewHeaderViewWithTitle:@"控制器信息"];
            }else if (section == 2) {
                view = [self tableViewHeaderViewWithTitle:@"门信息"];
            }
            
            break;
        default:
            if (section == 0) {
                view = [self tableViewHeaderViewWithTitle:@"门禁控制器"];
            }else if (section == 1) {
                view = [self tableViewHeaderViewWithTitle:@"控制器关联门"];
            }
            break;
    }
    
    return view;
}

- (UIView *)tableViewHeaderViewWithTitle:(NSString *)title {
    UIView *headView = [[UIView alloc]init];
    headView.backgroundColor = [UIColor clearColor];
    headView.width = kScreen_W;
    headView.height = k_heightForHeaderInSection;
    
    UIView *highlightedView = [[UIView alloc]init];
    highlightedView.backgroundColor = kALSHightBlueColor;
    highlightedView.width = 4;
    highlightedView.height = headView.height * 0.4;
    highlightedView.x = 10;
    highlightedView.y = (headView.height - highlightedView.height ) / 2;
    highlightedView.layer.cornerRadius = 1;
    highlightedView.layer.masksToBounds = YES;
    [headView addSubview:highlightedView];
    
    UILabel *lable = [[UILabel alloc]init];
    lable.text = title;
    lable.font = [UIFont systemFontOfSize:15];
    lable.textColor = [UIColor whiteColor];
    [lable sizeToFit];
    lable.x = highlightedView.right + 5;
    lable.y = (headView.height - lable.height) / 2;
    [headView addSubview:lable];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return k_heightForHeaderInSection;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"----%@",indexPath);
}


#pragma mark - LGDCDelegate
- (void)reloadTableViewWithNumberOfDoor:(NSUInteger)number {
    
    NSMutableArray *doorsInfoArr = self.tableDataArr[1];
    // 增
    if (doorsInfoArr.count < number) {
        LGDCCellContent *lastContent = [doorsInfoArr lastObject];
        
        for (NSUInteger i = doorsInfoArr.count; i < number; i++) {
            
            LGDCCellContent *doorInfo = [[LGDCCellContent alloc]init];
            doorInfo.title = [NSString stringWithFormat:@"门%lu",i + 1];
            doorInfo.placehold = lastContent.placehold;
            doorInfo.cellClass = lastContent.cellClass;
            doorInfo.cellHeight = lastContent.cellHeight;
            doorInfo.presentationText = lastContent.presentationText;
            [doorsInfoArr addObject:doorInfo];
        }
    }else if (doorsInfoArr.count > number ) {
        // 减
        [doorsInfoArr removeObjectsInRange:NSMakeRange(number, doorsInfoArr.count- number)];
    }else {
        // 不增不减
        return;
    }
    
    NSIndexSet *indeSet = [[NSIndexSet alloc]initWithIndex:1];
    [self.controllerInfoTableView reloadSections:indeSet withRowAnimation:(UITableViewRowAnimationAutomatic)];
}

- (void)hiddenPresentationWithContent:(LGDCCellContent *)content {
    if (content.cellHeight == k_height_editCell_Default) {
        return;
    }
    content.presentationText = nil;
    content.cellHeight = k_height_editCell_Default;
    [self.controllerInfoTableView reloadRowsAtIndexPaths:@[content.indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
}

- (void)showPresentation:(LGDCCellContent *)content {
    if (content.cellHeight == k_height_editCell_Presentation) {
        return;
    }
    
    content.cellHeight = k_height_editCell_Presentation;
    [self.controllerInfoTableView reloadRowsAtIndexPaths:@[content.indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
}

- (BOOL)validateWithContent:(LGDCCellContent *)content {
    
    // 门信息 只判断是否为空 空：NO 非空：Yes
    
    if (content.indexPath.section == k_section_door) {
        if (content.contentText.length != 0) {
            NSMutableArray *doorsInfoArr = self.tableDataArr[k_section_door];
            for (int i=0; i<doorsInfoArr.count; i++) {
                [self hiddenPresentationWithContent:doorsInfoArr[i]];
            }
            return YES;
        }
        return NO;
    }
    
    // 控制器信息 － port为空或者为纯数字：yes
    if (content.indexPath.row == k_port) {
        
        if (content.contentText.length == 0) {
            [self hiddenPresentationWithContent:content];
            return YES;
        }
        
        NSScanner *scan = [NSScanner scannerWithString:content.contentText];
        int val;
        if ([scan scanInt:&val] && [scan isAtEnd]) {
            // port正确 纯数字 隐藏提示
            [self hiddenPresentationWithContent:content];
            return YES;
        }else {
            // port错误
            content.presentationText = @"包含非数字字符";
            [self showPresentation:content];
        }
        
    }else if (content.indexPath.row == k_sn) {
        // 控制器信息 － sn正确：yes
        NSPredicate * predicate = [NSPredicate predicateWithFormat: @"SELF MATCHES %@", @"^ALS[1|2|4|6|8]\\d{7}$"];
        if ([predicate evaluateWithObject:content.contentText]) {
            //匹配成功 取消提示
            NSString *numberStr = [content.contentText substringWithRange:NSMakeRange(3, 1)];
            [self reloadTableViewWithNumberOfDoor:[numberStr integerValue]];
            [self hiddenPresentationWithContent:content];
            return YES;
        }else {
            //没匹配上 不是sn
            if (content.contentText.length == 0) {
                if (![content.presentationText isEqualToString:@"此项不可为空"]) {
                    content.presentationText = @"此项不可为空";
                    content.cellHeight = k_height_editCell_Default;
                }
                
            }else {
                if (![content.presentationText isEqualToString:@"S/N错误"]) {
                    content.cellHeight = k_height_editCell_Default;
                    content.presentationText = @"S/N错误";
                }
            }
            [self showPresentation:content];
        }
        
    }else {
        if (content.contentText.length == 0) {
            //控制器信息  非port 内容为空
            content.presentationText = @"此项不可为空";
            [self showPresentation:content];
        }else {
            [self hiddenPresentationWithContent:content];
            return YES;
        }
    }
    
    return NO;
}

- (void)cellButtonClick {
    [self rightBatButtonClick:nil];
}

- (void)keyboardWillHide {
    [self.controllerInfoTableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    NSValue *value = userInfo[UIKeyboardFrameEndUserInfoKey];
    CGFloat keyBoardHeight = [value CGRectValue].size.height;
    //    NSLog(@"---%f",keyBoardHeight);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        CGFloat tableHeight = self.controllerInfoTableView.height;
        CGFloat cellBottom = self.editingCellBottom - self.controllerInfoTableView.contentOffset.y;
        if (tableHeight < cellBottom + keyBoardHeight) {
            CGFloat offsetY = self.editingCellBottom - (tableHeight - keyBoardHeight);
            [self.controllerInfoTableView setContentOffset:CGPointMake(0, offsetY) animated:YES];
        }
        
    });
    
    [self.controllerInfoTableView setContentInset:UIEdgeInsetsMake(0, 0, keyBoardHeight, 0)];
}

- (void)cellDidBeginEditing:(CGFloat)bottom {
    self.editingCellBottom = bottom;
}
- (void)cellDidBeginEditing:(CGFloat)bottom andIndexpath:(NSIndexPath *)indexPath {
    self.editingCellBottom = bottom;
    self.editingCellIndexPath = indexPath;
}

- (void)inputAccessoryViewCommitActionStyle:(LGInputAccessoryViewActionStyle)inputAccessoryViewActionStyle {
    switch (inputAccessoryViewActionStyle) {
        case LGInputAccessoryViewActionStyleComplete:
            [self.view endEditing:YES];
            break;
        case LGInputAccessoryViewActionStyleNext:
        {
            NSInteger section;
            NSInteger row;
            if (_editingCellIndexPath.row == _tableDataArr[_editingCellIndexPath.section].count - 1) {
                section = _editingCellIndexPath.section + 1;
                row = 0;
            }else {
                row = _editingCellIndexPath.row + 1;
                section =_editingCellIndexPath.section;
                
            }
            NSIndexPath *nextCellIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
            LGDCBaseCell *nextCell = [self.controllerInfoTableView cellForRowAtIndexPath:nextCellIndexPath];
            
            if ([nextCell isKindOfClass:[LGEditCell class]]) {
                LGEditCell *editCell = (LGEditCell *)nextCell;
                if (editCell.infoTextField.enabled == NO) {
                    self.editingCellIndexPath = nextCellIndexPath;
                    [self inputAccessoryViewCommitActionStyle:inputAccessoryViewActionStyle];
                    return;
                }
                [editCell.infoTextField becomeFirstResponder];
            }else {
                CGFloat offsetY = self.controllerInfoTableView.contentSize.height - (self.controllerInfoTableView.height - self.controllerInfoTableView.contentInset.bottom);
                [self.controllerInfoTableView setContentOffset:CGPointMake(0, offsetY) animated:YES];
                
            }
            
        }
            break;
        case LGInputAccessoryViewActionStylePrev:
        {
            NSInteger section;
            NSInteger row;
            if (_editingCellIndexPath.row == 0) {
                section = _editingCellIndexPath.section - 1;
                row = _tableDataArr[section].count - 1;;
                
                if (section == -1) {
                    return;
                }
            }else {
                row = _editingCellIndexPath.row - 1;
                section =_editingCellIndexPath.section;
            }
            
            if (section == 0 && row == 0) {
                [self.controllerInfoTableView setContentOffset:CGPointMake(0, 0) animated:YES];
            }
            
            NSIndexPath *prevCellIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
            LGDCBaseCell *prevCell = [self.controllerInfoTableView cellForRowAtIndexPath:prevCellIndexPath];
            
            if ([prevCell isKindOfClass:[LGEditCell class]]) {
                LGEditCell *editCell = (LGEditCell *)prevCell;
                if (editCell.infoTextField.enabled == NO) {
                    self.editingCellIndexPath = prevCellIndexPath;
                    [self inputAccessoryViewCommitActionStyle:inputAccessoryViewActionStyle];
                    return;
                }
                [editCell.infoTextField becomeFirstResponder];
            }
            
        }
            break;
        default:
            break;
    }
}
#pragma mark - load

- (void)setControllerInfoViewState:(LGControllerInfoViewState)controllerInfoViewState {
    
    _controllerInfoViewState = controllerInfoViewState;
    
    switch (controllerInfoViewState) {
        case LGControllerInfoViewShowState:
            [self setShowState];
            break;
            
        case LGControllerInfoViewEditState:
            [self setEditState];
            break;
            
        case LGControllerInfoViewAddState:
            [self setAddState];
            break;
            
        default:
            break;
    }
    
    [self.controllerInfoTableView reloadData];
    
}

#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//
//    UIView *view;
//
//    switch (self.controllerInfoViewState) {
//        case LGControllerInfoViewShowState:
////            if (section == 1) {
////                view = [self tableViewHeaderViewWithTitle:@"控制器信息"];
////            }else if (section == 2) {
////                view = [self tableViewHeaderViewWithTitle:@"门信息"];
////            }
//
//            break;
//        default:
//            if (section == 0) {
//                view = [[UIView alloc]init];
//                view.width = SCREEN_WIDTH;
//                view.height = 1;
//                CGFloat value = 115;
//                view.backgroundColor = UIColorMake(value, value, value);
//            }
////            else if (section == 1) {
////                view = [self tableViewHeaderViewWithTitle:@"控制器关联门"];
////            }
//            break;
//    }
//
//    return view;
//}

//NSString *const title = @"title";
//NSString *const placeholder = @"placeholder";
//NSString *const keyboardType = @"keyboardType";
//NSString *const contentText = @"contentText";
//NSString *const cellClass = @"cellClass";
//NSString *const cellHeight = @"cellHeight";

